<template>
  <div>
    <el-row>
      <el-col :span="20" :offset="2">
        <el-card style="width: 100%; margin-top: 20px;">
          <h1 style="text-align: center">我的购物车</h1>
          <el-divider></el-divider>
          <el-table :data="items" style="width: 100%;margin-top:30px;" stripe>
            <el-table-column >
              <template slot-scope="scope">
                <el-checkbox v-model="checked[scope.row.id]"
                            @change="check(scope.$index,scope.row.id)"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column 
              align="center" 
              label="图片">
              <template slot-scope="scope">
                <img :src="scope.row.productPic" style="width: 100px; height: 100px" class="user-avatar">
              </template>
            </el-table-column>
            <el-table-column 
              prop="productName" 
              align="center" 
              label="商品名称">
            </el-table-column>
            <el-table-column 
              prop="price" 
              align="center" 
              label="价格">
            </el-table-column>
            <el-table-column 
              prop="name" 
              align="center" 
              label="数量">
              <template slot-scope="scope">
                <el-input-number size="mini"
                  v-model="scope.row.quantity"
                  :min="1"
                  :max="10"
                  @change="(cur,old) => numChange(cur, old, scope.row.price,scope.row.id)"></el-input-number>
              </template>
            </el-table-column>

            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="moveOut(scope.$index, scope)">移除购物车</el-button>
                <el-button type="text" size="small" @click="toInfo(scope.row.productId)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>


          <!-- <el-row style="width: 890px">
            <el-col :span="12" style="text-align: center">
              <span style="font-weight: lighter">商品信息</span>
            </el-col>
            <el-col :span="3" style="text-align: center">
              <span style="font-weight: lighter">单价</span>
            </el-col>
            <el-col :span="4" style="text-align: center">
              <span style="font-weight: lighter">数量</span>
            </el-col>
            <el-col :span="2" style="text-align: center">
              <span style="font-weight: lighter">金额</span>
            </el-col>
            <el-col :span="3" style="text-align: center">
              <span style="font-weight: lighter">操作</span>
            </el-col>
          </el-row> -->
          <!-- <div style="height: 15px"></div>
          <div v-for="(item,index) in items" :key="index">
            <el-row>
              <el-col :span="1">
                <el-checkbox style="width: 950px" v-model="checked[item.id]"
                            @change="check(index,item.id)"></el-checkbox>
              </el-col>
              <el-col :span="23">
                <el-row style="width: 890px">
                  <el-col :span="3">
                    <el-image :src="item.url" style="height: 60px; width: 60px"></el-image>
                  </el-col>
                  <el-col :span="4">
                    <a @click="toInfo(item.id)" style="cursor: pointer;">
                      {{item.name}}
                    </a>
                  </el-col>
                  <el-col :span="5">
                    <div style="width: 100%;
                            white-space:normal;
                            word-break:break-all;
                            word-warp:break-word;">
                      <span v-for="(i,t) in item.attrMap" :key="t">{{t}}: {{i}}</span>
                    </div>
                  </el-col>
                  <el-col :span="2">
                    <span style="font-weight: bold">￥{{item.price}}</span>
                  </el-col>
                  <el-col style="width: 170px">
                    <el-input-number size="mini"
                                    v-model="item.quantity"
                                    :min="1"
                                    :max="5"
                                    @change="(cur,old) => numChange(cur, old, item.price,item.id)"></el-input-number>
                  </el-col>
                  <el-col :span="2">
                    <span style="font-weight: bold">￥{{numFilter(item.price, item.quantity)}}</span>
                  </el-col>
                  <el-col :span="2">
                    <el-button type="text" @click="moveOut(index,item.id,item.price,item.quantity)">移出购物车</el-button>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <el-divider></el-divider>
          </div> -->
          <el-card style="margin-top: 30px;background: #e5e5e5;">
            <!-- <el-row></el-row> -->
            <el-checkbox v-model="isAll" @change="allCheck">全选</el-checkbox>
            <span style="margin-left: 60%">已选商品<span style="color: #f40">{{select.length}}</span>件</span>
            <span style="margin-left: 5%">合计<span style="color: #f40">{{price}}</span><span v-if="price < 88" style="">（满88包邮）</span></span>
            <el-button v-if="select.length > 0"
                      style="background:#f40;
                    color: white;
                    font-weight: lighter;
                    float: right;
                    margin-top: -10px"
                      @click="buy">结算
            </el-button>
            <el-button v-else style="background:#3c3c3c;
            color: white;
            font-weight: lighter;
            float: right;
            margin-top: -10px"
                      disabled>结算
            </el-button>
          </el-card>
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>

<script>
  // import {mapGetters} from 'vuex'
  import {accAdd, accMul, subtr} from "../../utils/cal";
  import { cartList, updateQuantity, delProduct } from '@/api/cart'

  export default {
    name: "index",
    created() {
      this.cartList()
    },
    data() {
      return {
        items: [
        ],
        checked: {},
        select: [],
        price: 0,
        isAll: false,

      }
    },
    methods: {
      async cartList() {
        const res = await cartList()
        console.log("getContent",res)
        let data = res.data
        for(let i = 0; i <data.length; i++) {
          // this.checked[data[i].id] = false
          this.$set(this.checked, data[i].id, false)
          this.items.push(data[i])
        }
        console.log(this.checked)
        // this.recommends = recommendProductList
        // this.hots = hotProductList
        // this.products = productList
      },
      toInfo(id) {
        console.log("id",id)
        this.$router.push({path: '/product', query: {id: id}})
      },
      async numChange(curValue, oldValue, price, id) {
        // TODO 购物车数量改变

        await updateQuantity(id, curValue).then(() => {
          if (curValue > oldValue) {
            if (this.checked[id]) {
              this.price = accAdd(this.price, accMul(curValue - oldValue, price))
            }
          } else {
            if (this.checked[id]) {
              this.price = subtr(this.price, accMul(oldValue - curValue, price))
            }
          }
        })
      },
      allCheck(val) {
        if (val) {
          for (let i = 0; i < this.items.length; i++) {
            if (!this.checked[this.items[i].id]) {
              let mul = accMul(this.items[i].price, this.items[i].quantity)
              this.price = accAdd(this.price, mul)
              this.num += 1
              this.checked[this.items[i].id] = true
              this.select.push(this.items[i].id)
            }
          }
        } else {
          for (let i = 0; i < this.items.length; i++) {
            let mul = accMul(this.items[i].price, this.items[i].quantity)
            this.price = subtr(this.price, mul)
            this.num -= 1
            this.checked[this.items[i].id] = false
          }
          this.select = []
        }
      },

      numFilter(quantity, price) {
        return accMul(quantity, price)
      },

      moveOut(index, scope) {
        const { id, price, quantity, productName } = scope.row
        let arr = []
        arr.push(id)
        this.$confirm('确认移除商品：'+productName+'?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
            })
          .then(async() => {
            await delProduct(arr).then(() => {
              this.$message({
                type: 'success',
                message: '删除菜单成功'
              })
            })

            if (this.checked[id]) {
              this.price = subtr(this.price, accMul(price, quantity))
            }
            delete this.checked[id]
            this.items.splice(index,1)
            if (this.num == this.items.length) {
              this.isAll = true
            } else {
              this.isAll = false
            }

            this.select.splice(index, 1)
            console.log(this.checked)
          })
      },
      buy() {
        // TODO 购物车下单
        console.log("buy",this.select)
        this.$router.push({path: '/settlement', query: {cartIds: this.select}})
      },

      check(index, id) {
        if (this.checked[id]) {
          let mul = accMul(this.items[index].price, this.items[index].quantity)
          this.price = accAdd(this.price, mul)
          this.select.push(id)
        } else {
          let mul = accMul(this.items[index].price, this.items[index].quantity)
          this.price = subtr(this.price, mul)
          let j = 0;
          for (let i = 0; i < this.select.length; i++) {
            if (this.select[i] == id) {
              j = i
              break
            }
          }
          this.select.splice(j,1)
        }
        
        if (this.select.length == this.items.length) {
          this.isAll = true
        } else {
          this.isAll = false
        }
      },
    },
    /*computed: {
      ...mapGetters([
        'id'
      ])
    }*/
  }
</script>

<style scoped>

</style>
